<?php

namespace App\Http\Controllers\Admin;


use App\Http\Models\Nav;

class NavController extends CommonController{
   
    public function index(){
        $data = Nav::orderBy('nav_order', 'asc')->get();
        return view('admin.nav.index', ['data' => $data]);
    }
    
    public function create(){
        return view('admin.nav.add');
    }    
    
    public function store(){
        $input = \Input::except('_token');
        if ($input) {
            $rules = [
                'nav_name' => 'required',
                'nav_url' => 'required|active_url'
            ];

            $messages = [
                'nav_name.required' => '自定义导航栏名称不能为空！',
                'nav_url.required' => '链接不能为空！',
                'nav_url.active_url' => '不是有效的链接！',
            ];
            
            $validator = \Validator::make($input, $rules, $messages);
            if ($validator->passes()) {
                $r = Nav::create($input);
                if($r)
                    return redirect ('admin/navigation');
                else 
                    return back()->with ('errors', '创建失败，请稍后再试！');
            } else
                return back()->withErrors($validator);
        }
    }

    public function show(){
        
    }

    public function edit($nav_id){
        $data = Nav::find($nav_id);
        return view('admin.nav.edit', ['data' => $data]);
    } 
    
    public function update($nav_id){
        $input = \Input::except('_token', '_method');
        
        $rules = [
                'nav_name' => 'required',
                'nav_url' => 'required|active_url'
            ];

            $messages = [
                'nav_name.required' => '自定义导航栏名称不能为空！',
                'nav_url.required' => '链接不能为空！',
                'nav_url.active_url' => '不是有效的链接！',
            ];

        $validator = \Validator::make($input, $rules, $messages);
        if ($validator->fails()) 
            return back()->withErrors($validator);
        
        $r = Nav::where('nav_id', $nav_id)->update($input);
        
        return back()->with('errors', ($r) ? '自定义导航栏更新成功':'自定义导航栏更新失败，请稍后再试！');
    }

    public function destroy($nav_id){
        $r = User::where('nav_id', $nav_id)->delete();
        
        $data = [];
      
        $data['status'] = ($r) ? 0 : 1;
        $data['msg'] = ($r) ? '删除成功':'删除失败请稍后再试！';

        return $data;  
    }
    
}
